#!/usr/bin/env perl
#Copyright (c) 2010, Peter Healy
#This file is part of civscore-tools.

#notifer-general is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#civscore-tools is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with civscore-tools.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Std;
my $gnuplotVersion = `gnuplot --version`;
	if($gnuplotVersion eq ""){
		print "You don't have gnuplot\ntry: http://www.gnuplot.info/download.html\n";
		exit;
	}
	else{
		print "You have $gnuplotVersion";
	}
# Set our options
# -f = civscore.log input file
# -o = output file basename
# -t = the tag you are interested in

#not yet implemented
# -p = the player ids you are interested in

# Process command-line args
my %options;
getopts('f:o:t:', \%options);

my $civScoreFilename = $options{f} || "$ENV{HOME}/civscore.log";
	open FILE, '<', "$civScoreFilename" or die "Cannot open civscore.log file: $!";
	my $game_id;
	my %tag_ids;
	my %turn_years;
	my %player_ids;
	my $interested_tag;
#	my $interested_pid = 0;
	if($options{t} == 0){
		$interested_tag = 0; #the or statement below will always evaluate 0 as false, so you get gold even if you want population
	}
	else{
		$interested_tag = $options{t} || "14"; #default to tag 14, gold- everybody loves gold
	}
	print "You are interested in tag $interested_tag\n";
	
	my %graph_hash;
	while (<FILE>){ 
		if($_=~/^#/g){ #can rewrite this if logic as a switch
			#print "$_ is a comment\n";
			next;
		}
		if($_=~/id/g){
			my @line_items = split;
			$game_id = $line_items[1];
			next;
		}
		if($_=~/tag/g){
			my @line_items = split;
			$tag_ids{$line_items[1]} = $line_items[2];
			next;
		}
		if($_=~/turn/g){
			my @line_items = split;
			$turn_years{$line_items[1]} = $line_items[2];
			next;
		}
		if($_=~/addplayer/g){ #Doesn't give back correct graphs when player dies(delplayer) FIXME
			my @line_items = split;
			$player_ids{$line_items[2]} = join(' ',@line_items[3..$#line_items]);
			next;
		}
		if($_=~/data/g){
			#$interested_tag = showMenu();
			my @line_items = split;
			#print "$line_items[0] : turn: $line_items[1] tag: $line_items[2] pid: $line_items[3] value: $line_items[4]\n";
			#DBINSERT => schema values(game_id turn tag player data)
			#if($interested_pid == $line_items[3] && $interested_tag == $line_items[2]){
			#	print "$line_items[1] $line_items[4]\n"; # x:turn y:value of tag
			#}
			if($interested_tag == $line_items[2]){ #hash{turn#} = pid(val) pid(val)
				push @{$graph_hash{$line_items[1]}}, $line_items[4];
			}
			next;
		}
	}
close(FILE);

my $outputFile_basename = $options{o} || "$game_id-$tag_ids{$interested_tag}";

 open(OUTFILE1, ">$outputFile_basename.dat"); #open for write, overwrite

	print OUTFILE1 "#game_id: $game_id\n";			#hash comments ignored by gnuplot
	while ( my ($key, $value) = each(%tag_ids) ) {
	        print OUTFILE1 "#Tag id $key => $value\n";
	}
	#while ( my ($key, $value) = each(%turn_years) ) {
	#        print "Turn $key => ", abs($value);
	#	if($value<0){ print " BC\n";} else{print " AD\n";}
	#}
	while ( my ($key, $value) = each(%player_ids) ) {
	        print OUTFILE1 "#Player $key =>  $value\n";
	}
	foreach my $turn (sort {$a<=>$b} keys %graph_hash) {
	  print OUTFILE1 "$turn ";
	  my @values = @{$graph_hash{$turn}};
        print OUTFILE1 join ' ',@values;
	  print OUTFILE1 "\n";
	}
close(MYOUTFILE);

open(OUTFILE2, ">$outputFile_basename.gnuplot"); #open for write, overwrite

my @gnuplotCommands;
push(@gnuplotCommands,"set xlabel \"Turn\"\n");
push(@gnuplotCommands,"set ylabel \"$tag_ids{$interested_tag}\"\n");      
push(@gnuplotCommands, "plot ");
foreach my $key (sort {$a<=>$b} keys %player_ids) {
	       push(@gnuplotCommands," \"$outputFile_basename.dat\" using 1:",$key+2," title \'",$player_ids{$key},"\' with lines, ");
	}

chop($gnuplotCommands[$#gnuplotCommands]);#get rid of trailing comma
chop($gnuplotCommands[$#gnuplotCommands]);#get rid of trailing comma

foreach(@gnuplotCommands){
print OUTFILE2 $_;
}
close(OUTFILE2);
print "Wrote out:\n$outputFile_basename.dat\n$outputFile_basename.gnuplot \n";
print "All you have to do now is run:\ngnuplot -persist $outputFile_basename.gnuplot to manipulate the graph\n";
print "This command will be run for you immediately\n";
system("gnuplot -persist $outputFile_basename.gnuplot");
# plot Inorder of player keys: 1:1 as turn 1:{pid+1} using title $pids{$pid} with lines

sub showMenu{
print "civscore2gnuplot: Choose a tag menu\nYou can choose which piece of data you are interested in\n";
foreach my $tag_id (sort {$a<=>$b} keys %tag_ids ) {
	        print "Tag id number ($tag_id): $tag_ids{$tag_id}\n";
	}
	chomp( my $input = <> );
return $input;
}

